package com.bjpowernode.handler;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @ClassName Interceptor
 * @Description
 * @Author hhwu
 * @Date 2022/3/15 16:13
 * Version 1.0
 **/
public class MyInterceptor implements HandlerInterceptor {
    /**
     * @Author hhwu
     * @Description //TODO 拦截器类，拦截用户的请求,preHandler是最重要的。
     * @Date 16:25 2022/3/15
     **/

    private long btime = 0;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 预处理方法，在处理器执行前执行，handler是被拦截的处理器对象。是整个项目的入口、门户
         * 返回值为true时，请求通过拦截器，可以执行处理器方法
         * 返回值为false时，请求不通过拦截器,请求到此就截止了！不可以执行处理器方法，也执行不了拦截器的postHandle和afterCompletion方法
         * @Date 16:42 2022/3/15
         * @Param [request, response, handler]
         * @return boolean
         **/

        btime = System.currentTimeMillis();
        //计算的业务逻辑，根据计算结果返回true或false

        System.out.println("preHandle");
        //给浏览器返回结果
//        request.getRequestDispatcher("/tips.jsp").forward(request, response);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO modelandview是处理器方法的返回值。
         * postHandle在处理器方法之后执行，能够对modelandview重点数据和视图进行进一步修改.
         * 用的较少
         *
         * @Date 17:08 2022/3/15
         * @Param [request, response, handler, modelAndView]
         * @return void
         **/
        System.out.println("postHandle");
//        对原来的dosome执行结果进行调整
        if (mv != null){
            mv.addObject("mydate", new Date());
            mv.setViewName("other");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        System.out.println("afterCompletion");
        long etime = System.currentTimeMillis();
        System.out.println("计算从prehandle到请求处理完成的时间："+(etime - btime));
    }
}
